package com.tanhua.backmanage.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.backmanage.mapper.ManagerMapper;
import com.tanhua.backmanage.pojo.Manager;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ManagerService {

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    public String login(String username, String password, String code, String uuid) {

        //校验验证码
        String redisCode = this.redisTemplate.opsForValue().get(uuid);
        if (!StringUtils.equals(code, redisCode)) {
            System.out.println("验证码错误");
            return null; //验证码错误

        }
        redisTemplate.delete(redisCode);

        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", password);
        Manager manager = this.managerMapper.selectOne(queryWrapper);
        System.out.println("manager = " +manager);
        if (manager == null) {
            System.out.println("用户名和密码错误");
            return null;//用户名和密码错误
        }

        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", manager.getId());
        claims.put("username", manager.getUsername());
        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();

        // 6.用户对象存入redis
        String user = JSON.toJSONString(manager);
        String reidsKey = "123456";
        redisTemplate.opsForValue().set(reidsKey, token, Duration.ofHours(4));
        return token;
    }


    public Manager queryManagerByToken(String token) {
        // 通过token解析数据
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        Manager manager = new Manager();
        manager.setId(Long.valueOf(body.get("id").toString()));
        /*String manager = redisTemplate.opsForValue().get(token);
        if (manager == null) {
            return null;
        }
        // 续期
        redisTemplate.opsForValue().set(token, manager, Duration.ofHours(4));
        return JSON.parseObject(manager, Manager.class);*/
        return manager;


      /*  // 通过token解析数据
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();

        Manager manager = new Manager();
        manager.setId(Long.valueOf(body.get("id").toString()));

        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", manager.getId());

        manager = this.managerMapper.selectOne(queryWrapper);
        return manager;
*/
    }

}
